#!/bin/bash

# --- Configuration ---
JAR_PATH="aibox-pro.jar"
LOG_FILE="app.log"
PID_FILE="app.pid"
# ---------------------

echo "Starting the application..."

if [ ! -f "$JAR_PATH" ]; then
    echo "ERROR: JAR file not found at $JAR_PATH"
    exit 1
fi

# Check if the application is already running
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p $PID > /dev/null; then
        echo "WARN: Application is already running with PID: $PID"
        exit 0
    else
        echo "WARN: Stale PID file found. Removing it."
        rm "$PID_FILE"
    fi
fi

# Start the application in the background with prod profile
nohup java -jar "$JAR_PATH" --spring.profiles.active=prod > "$LOG_FILE" 2>&1 &

# Get the PID of the last background process and save it
PID=$!
echo $PID > "$PID_FILE"

sleep 2

# Verify that the process is running
if ps -p $PID > /dev/null; then
    echo "Application started successfully with PID: $PID. Log is being written to $LOG_FILE"
else
    echo "ERROR: Application failed to start. Please check the log file '$LOG_FILE' for details."
    rm "$PID_FILE" # Clean up pid file on failure
    exit 1
fi
